import React, { useState, useEffect, useRef } from 'react';

interface CountdownTimerProps {
  createTime: string; // 接口返回的创建时间，格式为 ISO 8601 字符串
  className?: string; // 自定义类名
  onchange: (v: boolean) => void;
}

export default function CountdownTimer({ createTime, className, onchange }: CountdownTimerProps) {
  const [timeLeft, setTimeLeft] = useState<{
    hours: number;
    minutes: number;
    seconds: number;
    milliseconds: number;
  }>({ hours: 0, minutes: 0, seconds: 0, milliseconds: 0 });
  const [isExpired, setIsExpired] = useState(false);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // 清除之前的定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }

    // 计算剩余时间
    const calculateTimeLeft = () => {
      const createDate = new Date(createTime);
      const now = new Date();
      const expirationTime = new Date(createDate.getTime() + 30 * 60 * 1000); // 30分钟后
      // 如果已经过期
      if (now >= expirationTime) {
        setTimeLeft({ hours: 0, minutes: 0, seconds: 0, milliseconds: 0 });
        setIsExpired(true);
        onchange(true);
        return;
      }

      // 计算剩余毫秒数
      const diff = expirationTime.getTime() - now.getTime();

      // 计算时、分、秒、毫秒
      const hours = Math.floor(diff / 3600000);
      const minutes = Math.floor((diff % 3600000) / 60000);
      const seconds = Math.floor((diff % 60000) / 1000);
      const milliseconds = Math.floor(diff % 1000);

      setTimeLeft({ hours, minutes, seconds, milliseconds });
    };

    // 立即计算一次
    calculateTimeLeft();

    // 每10毫秒更新一次
    timerRef.current = setInterval(calculateTimeLeft, 10);

    // 组件卸载时清除定时器
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [createTime]);

  // 格式化数字为两位数
  const formatNumber = (num: number) => num.toString().padStart(2, '0');

  // 格式化毫秒为三位数
  // const formatMilliseconds = (ms: number) => ms.toString().padStart(3, '0').slice(0, 3);

  return (
    <div className="d-flex-c">
      {timeLeft.minutes < 5 && (
        <div className="animated-element text-center text-color-white mb-10 font-size-14 font-widget-600">
          温馨提示：链接即将失效
        </div>
      )}
      <div className={`countdown-box ${className || ''} ${isExpired ? 'opacity-50' : ''}`}>
        <span>{0}</span>天<span>{formatNumber(timeLeft.hours)}</span>时<span>{formatNumber(timeLeft.minutes)}</span>分
        <span>{formatNumber(timeLeft.seconds)}</span>秒
      </div>
    </div>
  );
}
